﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;

namespace AMix
{
    public partial class MijlocFixFrm : FrmWorkspace
    {
        private Int32 AnulCurent = 0;
        private Int32 LunaCurenta = 0;
        private Boolean IstoricAmortizare = false;
        private Int32 cate = 0;
        private const Int32 Limita = 200000;
        private Boolean MFStyle = true;
        public MijlocFixFrm(ModuleClass mInfo, Boolean mf)
            : base(mInfo)
        {
            MFStyle = mf;
            InitializeComponent();


            this.HandleTiparire += new EventHandler(MijlocFixFrm_HandleTiparire);
            this.HandleRezumat += MijlocFixFrm_HandleRezumat;
            regimuriAmortizareBindingSource.List.Add(new RegimuriAmortizare("Fara Amortizare", 0));
            regimuriAmortizareBindingSource.List.Add(new RegimuriAmortizare("Liniar", 1));
            regimuriAmortizareBindingSource.List.Add(new RegimuriAmortizare("Degresiv", 2));
            regimuriAmortizareBindingSource.List.Add(new RegimuriAmortizare("Accelerat", 3));
            if (MFStyle)
            {
                TipMijlocFixBindingSource.List.Add(new RegimuriAmortizare("Mijloc Fix", 0));
                TipMijlocFixBindingSource.List.Add(new RegimuriAmortizare("Mijloc Fix Compus", 1));
                TipMijlocFixBindingSource.List.Add(new RegimuriAmortizare("Mijloc Fix Componenta", 2));
                inFolosintaCB.Visible = false;
                IntrareDTP.Visible = false;
                IntratL.Visible = false;
                cantitateOILabel.Visible = false;
                cantitateOITextBox.Visible = false;
            }
            else
            {
                TipMijlocFixBindingSource.List.Add(new RegimuriAmortizare("Obiect de inventar", 3));
                TipMijlocFixBindingSource.List.Add(new RegimuriAmortizare("Seturi Obiecte de inventar", 4));
                Text = "Fisa Obiectului de Inventar";
                splitContainerPrincipal.Panel1Collapsed = true;
                iDStareLabel.Visible = false;
                iDStareCB.Visible = false;
                MFCarPanel.Visible = false;
                IntrareDTP.Visible = true;
                IntratL.Visible = true;
                ValoareObInvTB.Visible = true;
                label5.Visible = true;
                label4.Visible = true;
                Width = 650;
                cantitateOILabel.Visible = true;
                cantitateOITextBox.Visible = true;
            }
            //desi nu este cazul deoarece macheta este doar in consultare
            eSRPDataSet.AmixRegistru.CantitateOIColumn.DefaultValue = 1;
            eSRPDataSet.AmixRegistru.InFolosintaColumn.DefaultValue = true;
            //ReadOnly = true;
            
        }

        private void MijlocFixFrm_HandleRezumat(object sender, EventArgs e)
        {
            Int32 selID = -1;
            if (amixRegistruBindingSource.Current != null)
            {
                ESRPDataSet.AmixRegistruRow prr = ((DataRowView)amixRegistruBindingSource.Current).Row as ESRPDataSet.AmixRegistruRow;
                selID = (Int32)prr.IDMijlocFix;
            }
            MijlocFixRezumatFrm frm = new MijlocFixRezumatFrm(ModuleInfo, null, selID,MFStyle
                /*, AfiseazaDoarDocumenteleCurente, LunaCurenta, AnulCurent, -1, -1, -1, FelDocument, FSRow.GestiuneCantitativa*/);
            frm.SelectionAddOn = true;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (frm.selectedDataRow != null)
                {

                    amixRegistruBindingSource.RemoveFilter();
                    ESRPDataSet.AmixRegistruRow pr = frm.selectedDataRow.Row as ESRPDataSet.AmixRegistruRow;
                    try
                    {
                        amixRegistruBindingSource.EndEdit();
                    }
                    catch (Exception)
                    {
                        amixRegistruBindingSource.CancelEdit();
                    }
                    amixRegistruBindingSource.MoveFirst();
                    int posCautat = amixRegistruBindingSource.Find("IDMijlocFix", pr.IDMijlocFix.ToString());
                    if (posCautat!=-1)
                        amixRegistruBindingSource.Position = posCautat;
                    amixRegistruBindingSource.ResetCurrentItem();
                    SetTitle();
                }
            }
            EnableMainBrowseButton = true;
        }

        void MijlocFixFrm_HandleTiparire(object sender, EventArgs e)
        {
            DataRowView dr = ((DataRowView)amixRegistruBindingSource.Current);
            if (dr == null)
                return;

            List<BindingSource> listBS = new List<BindingSource>();
            List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();
            ESRPDataSet eSRPDS = new ESRPDataSet();
            Cursor.Current = Cursors.AppStarting;
            String linia1 = String.Empty, linia2 = String.Empty;
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));


            PreviewRaportFrm frm = new PreviewRaportFrm("", null,ModuleInfo);
            //eSRPDataSet - este data setul cu care lucram

            foreach (BindingSource bs in listBS)
                if (bs != null) bs.Dispose();

            listBS.Clear();
            listBS.Add(new BindingSource(eSRPDS, "BalconSetup"));

            listTA.Clear();
            listTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[0].SelectCommand.CommandType = CommandType.Text;

            listTA[0].Fill(eSRPDS.BalconSetup);
            DateTime dt = DateTime.Now, dte = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

            String filtruTotal = String.Empty;

            DateTime dtp = new DateTime(AnulCurent,LunaCurenta,1);
            DateTime primazi = new DateTime(dtp.Year, dtp.Month, 1);
            primazi = primazi.AddMonths(1).AddDays(-1);
            String strComanda = "SELECT * FROM [AmixViewAll] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [IDMijlocFix]=" + dr["IDMijlocFix"].ToString() +
                " ORDER BY [An], [Luna]";

            
            listTA.Add(new SqlDataAdapter(strComanda, cmd.Connection));
            listBS.Add(new BindingSource(eSRPDS, "AmixViewRegistru"));
            listTA[1].SelectCommand.CommandType = CommandType.Text;

            listTA[1].Fill(eSRPDS.AmixViewRegistru);

            frm.NumeRaport = "FisaMijlocFix.rdlc";
            frm.dataloadHandler += new LoadDataHandler(frm_dataloadHandler);
            listBS[1].Sort = "[An],[Luna]";
            frm.AddDataSource("ESRPDataSet_AmixViewRegistru", listBS[1]);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);

            frm.AddParameter("Linia1", linia1, true);
            frm.AddParameter("Linia2", linia2, true);
            frm.AddParameter("Centralizat", "False", true);
            frm.AddParameter("Grupare", "Gestionar", true);
            frm.AddParameter("An", AnulCurent.ToString(), true);
            frm.AddParameter("Luna", LunaCurenta.ToString(), true);
            String[] tab = new String[6];
            Object ret = GetSetupValue("BalconSetup", "Linia1Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                tab[0] = ret.ToString();
            else
                tab[0] = String.Empty;
            ret = GetSetupValue("BalconSetup", "Linia2Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                tab[1] = ret.ToString();
            else
                tab[1] = String.Empty;
            ret = GetSetupValue("BalconSetup", "Linia3Stanga", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                tab[2] = ret.ToString();
            else
                tab[2] = String.Empty;
            ret = GetSetupValue("BalconSetup", "Linia1Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                tab[3] = ret.ToString();
            else
                tab[3] = String.Empty;
            ret = GetSetupValue("BalconSetup", "Linia2Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                tab[4] = ret.ToString();
            else
                tab[4] = String.Empty;
            ret = GetSetupValue("BalconSetup", "Linia3Dreapta", ModuleInfo.CodUnitate, cmd.Connection);
            if (ret != null && ret != DBNull.Value)
                tab[5] = ret.ToString();
            else
                tab[5] = String.Empty;

            frm.AddParameter("Header", tab, true);

            frm.SetWindowFormat(true);


            foreach (SqlDataAdapter da in listTA)
                if (da != null) da.Dispose();
            listTA.Clear();
            frm.MdiParent = this.MdiParent;
            frm.Show();
            cmd.Dispose();
            InchideConexiune(cmd.Connection);


            Cursor.Current = Cursors.Default;
        }

        void frm_dataloadHandler(object sender, Microsoft.Reporting.WinForms.SubreportProcessingEventArgs args)
        {
            ESRPDataSet eSRPDS = new ESRPDataSet();
            BindingSource bs = null;
            SqlDataAdapter ta = null;
            SqlConnection sqlConn = DeschideConexiune(workConnString);

        
            if (args.ReportPath == "FisaMijlocFixSubreport")
            {
                String IDMijlocFix = args.Parameters["IDMijlocFix"].Values[0];
                Int16 Luna = Convert.ToInt16(args.Parameters["Luna"].Values[0]);
                Int16 An = Convert.ToInt16(args.Parameters["An"].Values[0]);
                bs = new BindingSource(eSRPDS, "AmixFisaMijlocFixView");
                String strComanda = "SELECT * FROM [AmixFisaMijlocFixView] WHERE [IDMijlocFix] = " + IDMijlocFix +
                    ((An * 100 + Luna != 0) ?
                    " AND [An]*100+[Luna]<=" + (An * 100 + Luna).ToString() : "");
                ta = new SqlDataAdapter(strComanda, sqlConn);
                ta.Fill(eSRPDS.AmixFisaMijlocFixView);
                if (bs.Count == 0)
                {
                    ESRPDataSet.AmixFisaMijlocFixViewRow rd = ((DataRowView)bs.AddNew()).Row as ESRPDataSet.AmixFisaMijlocFixViewRow;
                    rd.NumarDoc = 0;
                    rd.Debit = 0;
                    rd.Credit = 0;
                    rd.NrInventar = "";
                    rd = ((DataRowView)bs.AddNew()).Row as ESRPDataSet.AmixFisaMijlocFixViewRow;
                    rd.NumarDoc = 0;
                    rd.Debit = 0;
                    rd.Credit = 0;
                    rd.NrInventar = "";
                    rd = ((DataRowView)bs.AddNew()).Row as ESRPDataSet.AmixFisaMijlocFixViewRow;
                    rd.NumarDoc = 0;
                    rd.Debit = 0;
                    rd.Credit = 0;
                    rd.NrInventar = "";
                    rd = ((DataRowView)bs.AddNew()).Row as ESRPDataSet.AmixFisaMijlocFixViewRow;
                    rd.NumarDoc = 0;
                    rd.Debit = 0;
                    rd.Credit = 0;
                    rd.NrInventar = "";
                    rd = ((DataRowView)bs.AddNew()).Row as ESRPDataSet.AmixFisaMijlocFixViewRow;
                    rd.NumarDoc = 0;
                    rd.Debit = 0;
                    rd.Credit = 0;
                    rd.NrInventar = "";

                }
                args.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("ESRPDataSet_AmixFisaMijlocFixView", bs));

            }

            InchideConexiune(sqlConn);
            if(ta!=null)
                ta.Dispose();
        }

        private void Setup(SqlConnection wConn)
        {

            Object ret = GetSetupValue("AmixSetup", "LunaCurenta", ModuleInfo.CodUnitate, wConn);
            if (ret != null && ret != DBNull.Value)
                LunaCurenta = (Int16)ret;
            else
            {
                while (ret == null)
                {
                    MessageBox.Show("Modulul Amix nu a fost configurat. \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    AmixSetupFrm frm = new AmixSetupFrm(ModuleInfo);
                    frm.ShowDialog();
                    ret = GetSetupValue("AmixSetup", "LunaCurenta", ModuleInfo.CodUnitate, wConn);
                }
            }
            LunaCurenta = (Int16)ret;
            Object retObj = GetSetupValue("AmixSetup", "AnulCurent", ModuleInfo.CodUnitate, wConn);
            if (retObj != null && retObj != DBNull.Value)
                AnulCurent = Convert.ToInt32(retObj);

            retObj = GetSetupValue("AmixSetup", "IstoricAmortizare", ModuleInfo.CodUnitate, wConn);
            if (retObj != null && retObj != DBNull.Value)
                IstoricAmortizare = Convert.ToBoolean(retObj);

            if (LunaCurenta == 0)
            {
                MessageBox.Show("Modulul Amix nu a fost configurat corect (Luna curenta=0). \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                return;
            }
            Boolean dispAmo = false;
            retObj = GetSetupValue("AmixSetup", "AfiseazaAmortizare", ModuleInfo.CodUnitate, wConn);
            if (retObj != null && retObj != DBNull.Value)
                dispAmo = Convert.ToBoolean(retObj);
            if (MFStyle)
            {
                splitContainerPrincipal.Panel1Collapsed = !dispAmo;
                if(!dispAmo)
                    Width = 600;
            }
            SetInfoLunaAnul(LunaCurenta.ToString() + "," + AnulCurent.ToString());
            UMCB.Visible = !MFStyle;
            UMLabel.Visible = !MFStyle;
        }

        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {
            Salvare();
            AmixSetupFrm frm = new AmixSetupFrm(ModuleInfo);
            frm.ShowDialog();
            this.OnActivated(null);
            ///actualizare unitate la copi
            foreach (Form frmChild in this.MdiParent.MdiChildren)
            {
                //if (frmChild != this)
                ((StudioForm)frmChild).SetCurentMonth(ModuleInfo.CodUnitate);
            }
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            Setup(con);
            InchideConexiune(con);
        }

        private void MijlocFixFrm_Load(object sender, EventArgs e)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [AmixAmortizare] a JOIN [AmixRegistru] b ON a.[IDMijlocFix]=b.[IDMijlocFix] WHERE [CodUnitate]= " +ModuleInfo.CodUnitate.ToString(), con);
            cate = Convert.ToInt32(cmd.ExecuteScalar());
            Setup(con);
            this.jurnaleTableAdapter.Connection = con;
            this.jurnaleTableAdapter.Fill(this.eSRPDataSet.Jurnale,ModuleInfo.CodUnitate);

            this.unitatiMasuraTableAdapter.Connection = con;
            this.unitatiMasuraTableAdapter.Fill(this.eSRPDataSet.UnitatiMasura);
            this.amixGestionariTableAdapter.Connection = con;
            this.amixGestionariTableAdapter.Fill(this.eSRPDataSet.AmixGestionari);
            conturiTableAdapter.Connection = con;
            conturiTableAdapter.FillByTerminal(eSRPDataSet.Conturi, ModuleInfo.CodUnitate);
            this.amixPrincipalViewTableAdapter.Connection = con;
            this.amixPrincipalViewTableAdapter.Fill(this.eSRPDataSet.AmixPrincipalView);
            amixTipModDocumentTableAdapter.Connection = con;
            amixTipModDocumentTableAdapter.FillAll(eSRPDataSet.AmixTipModDocument);
            this.viewDocumenteInModuleTableAdapter.Connection = con;
            this.viewDocumenteInModuleTableAdapter.Fill(this.eSRPDataSet.ViewDocumenteInModule);
            this.amixDocumenteTableAdapter.Connection = con;
            this.amixDocumenteTableAdapter.Fill(this.eSRPDataSet.AmixDocumente, ModuleInfo.CodUnitate, (short)(MFStyle?0:3),(short)(MFStyle?2:5));
            this.amixAmortizareTableAdapter.Connection = con;
            if (cate < Limita && MFStyle)
            {
                if (IstoricAmortizare)
                    this.amixAmortizareTableAdapter.Fill(this.eSRPDataSet.AmixAmortizare);
                else
                    this.amixAmortizareTableAdapter.FillByAnLuna(this.eSRPDataSet.AmixAmortizare, AnulCurent, LunaCurenta);
            }
            this.departamenteTableAdapter.Connection = con;
            departamenteTableAdapter.Fill(eSRPDataSet.Departamente, ModuleInfo.CodUnitate);
           
            this.amixCatalogTableAdapter.Connection = con;
            this.amixTipStareTableAdapter.Connection = con;
            this.amixTipStareTableAdapter.Fill(this.eSRPDataSet.AmixTipStare);
            
            this.amixCatalogTableAdapter.Fill(this.eSRPDataSet.AmixCatalog);
            this.amixRegistruTableAdapter.Connection = con;


            if(MFStyle)
                this.amixRegistruTableAdapter.Fill(this.eSRPDataSet.AmixRegistru, ModuleInfo.CodUnitate,0,2);
            else
                this.amixRegistruTableAdapter.Fill(this.eSRPDataSet.AmixRegistru, ModuleInfo.CodUnitate,3,5);

            InchideConexiune(con);

            //AddButton("Salveaza", global::ERPStudio.Properties.Resources.salvare, Salvare, ToolStripItemAlignment.Right, true);
            AddButton("Document nou", global::ERPStudio.Properties.Resources.document, Document_Nou, ToolStripItemAlignment.Right, false);
            if(MFStyle)
                AddButton("Componente", global::ERPStudio.Properties.Resources.briefcase, Componente, ToolStripItemAlignment.Right, false);
            listBndSourceMain.Add(amixRegistruBindingSource);
            listTableAdaptor.Add(amixRegistruTableAdapter.Adapter);


            amixRegistruAmixAmortizareBindingSource.Sort = "An,Luna";
            CompusCB_SelectedIndexChanged(this,null);


        }
        private void Document_Nou(object sender, EventArgs e)
        {
            DocAmixFrm frm = new DocAmixFrm(-2,ModuleInfo);
            frm.NrInventar = nrInventarTB.Text;
            frm.ShowDialog();
            this.amixDocumenteTableAdapter.Connection = DeschideConexiune(workConnString);
            this.SuspendLayout();
            this.documenteDGV.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.amixRegistruAmixDocumenteBindingSource)).BeginInit();
            this.amixDocumenteTableAdapter.Fill(this.eSRPDataSet.AmixDocumente, ModuleInfo.CodUnitate,(short)(MFStyle?0:3),(short)(MFStyle?2:5));
            ((System.ComponentModel.ISupportInitialize)(this.amixRegistruAmixDocumenteBindingSource)).EndInit();
            this.documenteDGV.ResumeLayout();
            amixRegistruAmixDocumenteBindingSource.ResetBindings(false);
            this.ResumeLayout();
        }

        private void Componente(object sender, EventArgs e)
        {
            DataRowView dr = ((DataRowView)amixRegistruBindingSource.Current);
            if (dr == null)
                return;
            ComponenteFrm frm = new ComponenteFrm(Convert.ToInt32(dr["IDMijlocFix"]),ModuleInfo);
            frm.MdiParent = this.MdiParent;
            frm.Show();
        }

        private void CompusCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            AnsambluCB.Visible = Convert.ToInt16(CompusCB.SelectedValue) == 2;
            labelDin.Visible = Convert.ToInt16(CompusCB.SelectedValue) == 2;
        }

        /// <summary>
        /// deschide documentul pe care se da click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        
        private void documenteDGV_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            Int32 codDoc = Convert.ToInt32(documenteDGV[iDDocumentColumn.Index, e.RowIndex].Value);
            DocAmixFrm frm = new DocAmixFrm(codDoc,ModuleInfo);
            frm.ShowDialog();
        }

        private void amixRegistruBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if(((BindingSource)sender).Current!=null)
            {
                ESRPDataSet.AmixRegistruRow rdar = ((DataRowView)((BindingSource)sender).Current).Row as ESRPDataSet.AmixRegistruRow;
                this.RegistruMFtoolTip.SetToolTip(this.durataNormataTB, (rdar.DurataAmortizare / 12).ToString() + " ani si " + (rdar.DurataAmortizare % 12).ToString() + " luni");
                this.RegistruMFtoolTip.SetToolTip(this.LuniAmortizareTB, (rdar.LuniAmortizate / 12).ToString() + " ani si " + (rdar.LuniAmortizate % 12).ToString() + " luni");
                
                if (cate > Limita)
                {
                    amixAmortizareTableAdapter.Connection = DeschideConexiune(workConnString);
                    amixAmortizareTableAdapter.FillByIDMijlocFix(eSRPDataSet.AmixAmortizare, rdar.IDMijlocFix);
                    InchideConexiune(amixAmortizareTableAdapter.Connection);
                }
            }
            if(!IstoricAmortizare)
                amixRegistruAmixAmortizareBindingSource.Filter = "[An]*100+[Luna]>=" + (AnulCurent * 100 + LunaCurenta).ToString();
        }

        private void amortizariDGV_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (e.ListChangedType != ListChangedType.Reset || amortizariDGV.Rows.Count <= 0)
                return;
            MyTrace(e.ListChangedType + "," + amortizariDGV.Rows.Count.ToString());
            foreach (DataGridViewRow dc in amortizariDGV.Rows)
            {
                Boolean isBlocat = true;
                if (dc.Cells["BlocatColumn"].Value != DBNull.Value)
                    isBlocat = Convert.ToBoolean(dc.Cells["BlocatColumn"].Value);
                if (isBlocat == true)
                {
                    amortizariDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.LightSalmon;
                }
                else
                {
                    amortizariDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.LightGray;
                }
            }
        }

        
        
    }
}
